var express = require('express');
const readline = require('readline');

var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var UserManager = require('./UserManager.js');



app.use('/', express.static('public'));


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

//导入所有题目
var questionList = require('./questions');
//服务器状态.
var serverType = {
    type: 0, //type = 1 已经开始答题了, type = 0 没开始答题.
    nowQuestion: null //当前题目.
}

//当前人员集合.
var connectList = []; //UserManager 集合

io.on('connection', function (socket) {

    var user = new UserManager(socket, serverType);

    user.listen(); //监听

    connectList.push(user);

    console.log('a user connected');

    socket.on('disconnect', function () {
        var arr = [];
        for (let s = 0; s < connectList.length; s++) {
            const user = connectList[s];
            if (user.id != socket.id) {
                arr.push(user);
            }
        }
        connectList = arr;
    });
});





http.listen(3000, function () {
    console.log('listening on *:3000');
});


rl.on('line', (input) => {
    //向每个连接的客户端发送消息.
    switch (input) {
        case 'start':
            startQuestion(); //开发发题.
            break;

        default:
            break;
    }

});


//============================开始答题===================================

function startQuestion() {
    if (serverType.type == 1) {
        console.log('已经开始答题了');
        return;
    }
    serverType.type = 1;
    var arr = getQuestionList(questionList, 4); //随机提取8道题
    //发送消息
    sendQuestion(arr, 0, function () {
        console.log('全部发完了');
        overQuestion();
        serverType.type = 0;
    });
}

//发送题目
function sendQuestion(arr, nowIndex, cb) {
    if (serverType.nowQuestion != null) {
        var obj = {
            type: 'rightQuestion',
            data: serverType.nowQuestion
        }
        var strText = JSON.stringify(obj);
        sendMessage(strText);
    }

    if (nowIndex >= arr.length) {
        serverType.nowQuestion = null;
        cb();
    } else {
        var question = arr[nowIndex]; //拿到当前题目
        serverType.nowQuestion = question;
        var temp = {
            id: question.id,
            name: question.name,
            answer: question.answer
        }
        var strText = JSON.stringify({
            type: 'sendQuestion',
            data: temp
        });
        sendMessage(strText);

        setTimeout(() => {
            sendQuestion(arr, nowIndex + 1, cb)
        }, 10000);
    }
}

//结束答题
function overQuestion() {
    var users = connectList.filter(t => {
        return t.name != null;
    });
    for (let i = 0; i < users.length; i++) {
        const user = users[i];
        console.log('名字:' + user.name + ',分数:' + user.rightAnswer.length);
    }

    var arr = getFilterArray(users);

    var obj = {
        type: 'sort',
        data: arr
    }

    var strText = JSON.stringify(obj);

    sendMessage(strText);

}

function getFilterArray(users) {
    var flg = true;
    while (flg) {
        flg = false;
        for (let i = 0; i < users.length - 1; i++) {
            const u1 = users[i];
            const u2 = users[i + 1];
            if (u1.number < u2.number) {
                users[i] = u2;
                users[i + 1] = u1;
                flg = true;
            }
        }
    }
    var arr = [];
    for (let s = 0; s < users.length; s++) {
        const user = users[s];
        var obj = {
            name: user.name,
            id: user.id,
            number: user.number
        }
        arr.push(obj);
    }
    console.log(arr);
    return arr;

}


//从总题库提取需要的乱序题目
function getQuestionList(arr, num) {
    var list = [];
    for (let i = 0; i < num; i++) {
        var z = parseInt(Math.random() * arr.length);
        var temp = arr[i];
        arr[i] = arr[z];
        arr[z] = temp;
    }
    for (let i = 0; i < num; i++) {
        const question = arr[i];
        list.push(question);
    }
    return list;
}
//=========================================================

//给所有登录的用户发送消息
function sendMessage(strText) {
    for (let i = 0; i < connectList.length; i++) {
        var user = connectList[i];
        if (user.name != null) {
            user.socket.emit('msg', strText);
        }
    }
}